import Vue from "vue";
import Vuex from "vuex";
// 安装插件
Vue.use(Vuex);
// 创建store对象
const store = new Vuex.Store({
  state: {
    cartList: [],
  },

  mutations: {
    addCount(state, payload) {
      payload.count += 1;
    },
    addToCart(state, payload) {
      payload.checked = true;
      state.cartList.push(payload);
    },
  },

  actions: {
    addCart(context, payload) {
      return new Promise((resolve, reject) => {
        //返回一个Promise
        // 添加之前 先判断数组中是否已经存在该商品
        // 根据iid查找
        let oldProduct = context.state.cartList.find(
          (item) => item.iid === payload.iid
        );
        // 判断oldProduct是否存在
        if (oldProduct) {
          context.commit("addCount", oldProduct); //已存在商品数量加1
          resolve("当前商品数量+1");
        } else {
          context.commit("addToCart", payload); //添加新商品
          resolve("添加成功");
        }
      });
    },
  },

  getters: {
    cartLength(state) {
      return state.cartList.length;
    },
    cartList(state) {
      return state.cartList;
    },
  },
});

// 导出store实例
export default store;
